package com.sansui.blog.controller;

import com.github.pagehelper.PageInfo;
import com.sansui.blog.pojo.SysConfig;
import com.sansui.blog.pojo.vo.BlogInfoQuery;
import com.sansui.blog.service.BlogService;
import com.sansui.blog.service.SysInfoService;
import com.sansui.blog.service.TagService;
import com.sansui.blog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @name: BlogTagController
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-05-10 15:42
 **/
@RestController
public class BlogTagController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysInfoService sysInfoService;

    @RequestMapping(value = {"/tags"})
    public ModelAndView typeIndex(@RequestParam(value = "tagId",required = false,defaultValue = "0")String id,
                                  @RequestParam(value = "pageNum",required = false,defaultValue = "1")String page,
                                  @RequestParam(value = "pageSize",required = false,defaultValue = "5")Integer pageSize,
                                  ModelAndView mv){
        if(!StringUtils.isNumeric(page)){
            mv.setViewName("/error/404");
            return mv;
        }

        if(!StringUtils.isNumeric(id)){
            mv.setViewName("/error/404");
            return mv;
        }

        Integer pageNum = Integer.valueOf(page);

        List<Map<String, Object>> tagInfo = tagService.countTagInfo();
        Long tagId = Long.valueOf(id);
        if(tagId <= 0){
            tagId = Long.valueOf(String.valueOf(tagInfo.get(0).get("tagid"))).longValue();
        }

        PageInfo<BlogInfoQuery> pageInfo = blogService.queryAllByPage(pageNum,pageSize,null,tagId,null);
        SysConfig sysConfig = sysInfoService.getSysSetting();

        mv.setViewName("theme/"+ sysConfig.getThemeName() +"/tags");
        mv.addObject("webname",sysConfig.getWebname());
        mv.addObject("activeTagId",tagId);
        mv.addObject("countTNum",blogService.countTNum(null,tagId));
        mv.addObject("pageInfo",pageInfo);
        mv.addObject("tags",tagInfo);
        return mv;
    }


}
